<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_SDouban
{
	public $m_CI = NULL;
	
	public $m_arrUser   = array();
	
	public $douban = null;
	
	public $douban_uid = null;
	
	public static $oauthUrl = 'sdouban';
	
	public static $apiUrl   = 'apikey'
	
	public function __construct($para = array())
	{
		
		$this->m_CI = &get_instance();
		
		$this->m_arrUser = $this->m_CI->my_member->getUser();
		
		if (empty($this->m_arrUser))
		{
			redirect('account/login');
			exit;
		}
		
		// 载入model
		$this->m_CI->load->model('account/account_m');
		
		// 载入session
		$this->m_CI->load->library('session');
		

		$this->loadPlatform();
		
		$this->getToken();

	}

	private function loadPlatform()
	{		
		// 生成一个豆瓣Oauth类实例
		$config = $this->m_CI->config->item('oauht2');
		$appConfig = $config['douban'];
	
	    $this->m_CI->load->library('Douban/MY_DoubanOauth',$appConfig);
		
		$this->douban = $this->m_CI->my_doubanoauth;
	}
	
	private function getToken()
	{
		$filter = array(
				'accountID' =>$this->m_arrUser['id'],
				'platformID' => DOUBAN_TYPE,
				);
		$acc2platList = $this->m_CI->account_m->getPlatfromList($filter);

		// 未绑定过任何
		if (empty($acc2platList))
		{
			redirect('douban/'.self::$apikey);
			exit;
		}
		
		// 未填写key 和secret
		if ($acc2platList[0]['myKey'] == null || $acc2platList[0]['mySecret'] == null)
		{
			redirect('douban/'.self::$apikey);
			exit;
		}
			
		
		//未绑定过独立key		
		if ($acc2platList[0]['myToken'] == null)
		{
			redirect('oauth2/'.self::$oauthUrl);
			exit;
		}
		
		// 绑定了但是过期了..
		if ($acc2platList[0]['myOutTime'] < date('Y-m-d H:i:s',time()))
		{
			redirect('oauth2/'.self::$oauthUrl);
			exit;
		}
		
		$this->douban->setAccessToken($acc2platList[0]['myToken']);
		$this->douban_uid = $acc2platList[0]['openID'];
	}
	
}
